package pop;

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.InputStream;
import javax.swing.JOptionPane;

/**
*
* 
*
*/

public class ReadMail {
  private String from;
  private String subject;
  private String body;
  private Message message;
  
  protected ReadMail(Message message) {
   this.message = message;
   
    try {
      InternetAddress fromAddress = (InternetAddress) message.getFrom()[0];

      from = fromAddress.getPersonal() + " (" +
        fromAddress.getAddress() + ")";
    } catch (Exception e) {
      from = "Remitente no disponible";
    }

    try {
      subject = message.getSubject();
    } catch (Exception e) {
      subject = "Asunto no disponible";
    }
    
    try {
        if( message.isMimeType("text/plain") )
        {
            body = message.getContent().toString();
        }
        else
        {
          Multipart mp  = (Multipart)message.getContent();
          InputStream is = mp.getBodyPart(0).getInputStream();
        
          StringBuffer sb = new StringBuffer();
          byte[] b = new byte[100000];
          int noChars = is.read(b);
          sb.append(new String(b, 0, noChars));
          body = sb.toString();
        }
    }
    catch( Exception e)
    {
        body = "Mensaje no disponible";
    }
  }
  
  public void read()
  {
    int res = JOptionPane.showConfirmDialog(null, "De: " + from + "\nAsunto: " + subject + "\n\n\tLeer este mensaje?");
    if( res == 0)
        this.readBody();
  }
  
  public static List getMails(Message[] messages) {
    List list = new ArrayList();
    for (int i = 0; i < messages.length; i++) {
       list.add(new ReadMail(messages[i]));
    }
    
    return list;
  }
  
  public void readBody()
  {
      try {
          JOptionPane.showMessageDialog(null,this.body, "Asunto: " + this.subject, JOptionPane.PLAIN_MESSAGE);
      }
      catch( Exception e )
      {
          System.out.println("Error al mostrar el mensaje");
      }   
  }
}